package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2020/9/22 10:32
 **/
@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        // 判断参数
        if(StringUtils.isEmpty(adUserDto.getName())||StringUtils.isEmpty(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据用户名称获取数据库中用户信息
        List<AdUser> list = list(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        // 不存在返回参数错误
        if(list==null || list.size()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        // 存在，将传入密码加密后 和 数据库中密码做对比
        AdUser adUser = list.get(0);
        String pswd = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes());
        if(pswd.equals(adUser.getPassword())){
            // 如果密码一致 颁发token
            String token = AppJwtUtil.getToken(adUser.getId().longValue());
            Map map = new HashMap<>();
            map.put("token",token);
            // 这两个信息不能返回给用户
            adUser.setPassword("");
            adUser.setSalt("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
